package com.hiltony.web.controller;

import com.hiltony.web.mapper.DietMapper;
import com.hiltony.web.mapper.HealthIndexMapper;
import com.hiltony.web.mapper.MedicalMapper;
import com.hiltony.web.mapper.MedicalRecordMapper;
import com.hiltony.web.model.*;
import com.hiltony.web.service.ContacterService;
import com.hiltony.web.service.MemberEventHistoryService;
import com.hiltony.web.service.MemberService;
import com.hiltony.web.service.UserService;
import org.apache.commons.io.DirectoryWalker;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * Created by YX on 2016/9/16.
 *
 */

@Controller
@RequestMapping("/member")
public class MemberController {

    @Resource
    private UserService userService;

    @Resource
    private MemberService memberService;

    @Resource
    private MemberEventHistoryService memberEventHistoryService;

    @Resource
    private ContacterService contacterService;

    @Resource
    private HealthIndexMapper healthIndexMapper;

    @Resource
    private MedicalMapper medicalMapper;

    @Resource
    private DietMapper dietMapper;

    @Resource
    private MedicalRecordMapper medicalRecordMapper;

    @RequestMapping("/listMember")
    public String toIndex(Member member, HttpServletRequest request, Model model) {
        List<Member> members = new ArrayList<Member>();

        members.addAll(memberService.getMemberList(member));
        model.addAttribute("memberList", members);
        return "member";

    }

    @RequestMapping("/getMemberInfo")
    @ResponseBody
    public UserInfo getUserInfo() {
        UserInfo userInfo = userService.getUserById(1);

        return userInfo;
    }

    @RequestMapping("/getMemberList")
    @ResponseBody
    public List<Member> getMemberList(Member member, HttpServletRequest request) {
        return memberService.getMemberList(member);
    }

    @RequestMapping(value = "/addMember", method = RequestMethod.POST)
    @ResponseBody
    public String addMember(@RequestBody Member member, HttpServletRequest request, Model model) throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
        if (member.getBirthdayStr() != null) {
            member.setBirthday(sdf.parse(member.getBirthdayStr()));
        }
        if (member.getCheckInDayStr() != null) {
            member.setCheckInDay(sdf.parse(member.getCheckInDayStr()));
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(member.getBirthday());
        Calendar current = Calendar.getInstance();

        int age = current.get(Calendar.YEAR) - calendar.get(Calendar.YEAR);
        calendar.add(Calendar.YEAR, age);
        if (calendar.after(current)) {
            age += 1;
        }
        member.setAge(age);
        member.setStatus(1);
        memberService.addMember(member);
        return "success";
    }

    @RequestMapping(value = "/updateMember", method = RequestMethod.POST)
    @ResponseBody
    public String updateMember(@RequestBody Member member, HttpServletRequest request, Model model) throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (member.getBirthdayStr() != null) {
            member.setBirthday(sdf.parse(member.getBirthdayStr()));
        }
        if (member.getCheckInDayStr() != null) {
            member.setCheckInDay(sdf.parse(member.getCheckInDayStr()));
        }

        if (member.getBirthday() != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(member.getBirthday());
            Calendar current = Calendar.getInstance();

            int age = current.get(Calendar.YEAR) - calendar.get(Calendar.YEAR);
            calendar.add(Calendar.YEAR, age);
            if (calendar.after(current)) {
                age += 1;
            }
            member.setAge(age);
        }

        memberService.updateMember(member);
        return "success";
    }

    @RequestMapping("/memberDetail")
    public String getMemberDetail(Member member, HttpServletRequest request, Model model) {

        model.addAttribute("member", memberService.getMemberById(member));
        MemberEventHistory memberEventHistory = new MemberEventHistory();
        memberEventHistory.setMemberId(member.getMemberId());
        List<MemberEventHistory> memberEventHistoryList = memberEventHistoryService.getMemberEventHistoryList(memberEventHistory);
        TreeMap<String, List<MemberEventHistory>> eventMap = new TreeMap<String, List<MemberEventHistory>>();
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD");
        for (MemberEventHistory event : memberEventHistoryList) {
            eventMap.putIfAbsent(sdf.format(event.getEventTime()), new ArrayList<>());
            eventMap.get(sdf.format(event.getEventTime())).add(event);
        }
        NavigableMap rmap = eventMap.descendingMap();

        Contacter contacter = new Contacter();
        contacter.setMemberId(member.getMemberId());
        model.addAttribute("contacters", contacterService.getContacterList(contacter));
        model.addAttribute("memberEvent", memberEventHistoryService.getMemberEventHistoryList(memberEventHistory));

        return "member_detail";

    }

    @RequestMapping("/memberHealthIndex")
    public String getMemberHealthIndex(Member member, HttpServletRequest request, Model model) {
        List<Member> memberList = memberService.getMemberList(new Member());
        model.addAttribute("memberList", memberList);
        HealthIndex healthIndex = new HealthIndex();
        Medical medical = new Medical();

        if (member != null && member.getMemberId() != null) {
            model.addAttribute("member", memberService.getMemberById(member));
            healthIndex.setMemberId(member.getMemberId());
            medical.setMemberId(member.getMemberId());
        } else if (memberList != null && memberList.size() > 0) {
            model.addAttribute("member", memberList.get(0));
            healthIndex.setMemberId(memberList.get(0).getMemberId());
            medical.setMemberId(memberList.get(0).getMemberId());
        } else {
            model.addAttribute("member", null);
        }
        model.addAttribute("healthIndexs", healthIndexMapper.getHealthIndexList(healthIndex));
        model.addAttribute("medicalList", medicalMapper.getMedicalList(medical));


        return "member_health_index";
    }

    @RequestMapping("/addOrUpdateMedical")
    public String addOrUpdateMedical(@RequestBody ArrayList<Medical> medicalList, HttpServletRequest request, Model model) {

        List<Medical> addList = new ArrayList<>();
        List<Medical> updateList = new ArrayList<>();
        for (Medical medical : medicalList) {
            if (medical.getId() == null) {
                addList.add(medical);
            } else if (!medical.getMedicalName().equals("请双击输入内容")) {
                updateList.add(medical);
            }
        }
        System.out.println(medicalList.size());
        if (addList.size() > 0) {
            medicalMapper.addMedicalList(addList);
        }
        if (updateList.size() > 0) {
            for (Medical medical : updateList) {
                medicalMapper.updateMedical(medical);
            }
        }
        return "member_health_index";
    }

    @RequestMapping("/addOrUpdateHealthIndex")
    public String addOrUpdateHealthIndex(@RequestBody ArrayList<HealthIndex> healthIndexList, HttpServletRequest request, Model model) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (HealthIndex healthIndex : healthIndexList) {
            try {
                healthIndex.setLogday(sdf.parse(healthIndex.getLogdayStr()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        List<HealthIndex> addList = new ArrayList<>();
        List<HealthIndex> updateList = new ArrayList<>();
        for (HealthIndex healthIndex : healthIndexList) {
            if (healthIndex.getId() == null) {
                addList.add(healthIndex);
            } else {
                updateList.add(healthIndex);
            }
        }
        System.out.println(healthIndexList.size());
        if (addList.size() > 0) {
            for (HealthIndex healthIndex : addList)
                healthIndexMapper.addHealthIndex(healthIndex);
        }
        if (updateList.size() > 0) {
            for (HealthIndex healthIndex : updateList) {
                healthIndexMapper.updateHealthIndex(healthIndex);
            }
        }
        return "member_health_index";
    }


    @RequestMapping("/healthDietIndex")
    public String getMemberHealthDietIndex(Member member, HttpServletRequest request, Model model) {

        List<Member> memberList = memberService.getMemberList(new Member());
        model.addAttribute("memberList", memberList);
        Diet diet = new Diet();

        if (member != null && member.getMemberId() != null) {
            model.addAttribute("member", memberService.getMemberById(member));
            diet.setMemberId(member.getMemberId());
        } else if (memberList != null && memberList.size() > 0) {
            model.addAttribute("member", memberList.get(0));
            diet.setMemberId(memberList.get(0).getMemberId());
        } else {
            model.addAttribute("member", null);
            diet.setMemberId(-1L);
        }
        model.addAttribute("food_type_list",dietMapper.getAllFootType());

        model.addAttribute("dietList", dietMapper.getDietList(diet));

        return "health_diet_index";

    }

    @RequestMapping("/DietDetailIndex")
    public String getDietDetailInfo(Diet diet, HttpServletRequest request, Model model) {


        model.addAttribute("diet",dietMapper.getDietBean(diet));
        Food food = new Food();
        food.setDietId(diet.getId());

        model.addAttribute("dietDetails", dietMapper.getFoodList(food));

        return "diet_detail";

    }

    @RequestMapping(value = "/addMemberHealthDietIndex", method = RequestMethod.POST)
    @ResponseBody
    public String addMemberHealthDietIndex(@RequestBody  Diet diet,HttpServletRequest request,Model model){
        SimpleDateFormat sdf  = new SimpleDateFormat("yyyy-mm-dd");
        try {
            diet.setDietTime(sdf.parse(diet.getDiteTimeStr()));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Double calorie = 0.0;
        for (Food food:diet.getDietDetail()){
            FoodType foodType = new FoodType();
            foodType.setFoodType(food.getFoodType());
            foodType = dietMapper.getFoodTypeInfo(foodType);
            if (foodType!=null){
                calorie+= (food.getFoodCount()==null?0:food.getFoodCount()/1000.00)*(foodType.getCalorie()==null?0:foodType.getCalorie());
            }
        }
        diet.setCalorie(calorie);
        dietMapper.addDiet(diet);
        List<Food> foods = diet.getDietDetail();
        for (Food food:foods){
            food.setDietId(diet.getId());
        }
        dietMapper.addFoodList(foods);
        return "success";

    }

    @RequestMapping(value = "/getAllFoodType")
    @ResponseBody
    public Map getFoodTypeList(){

        Map<String,Object> result =  new HashMap<String,Object>();

        result.put("foodTypeList",dietMapper.getAllFootType());
        return result;
    }

    @RequestMapping("/healthDiseaseRecordIndex")
    public String getMemberHealthRecordIndex(Member member, HttpServletRequest request, Model model){
        List<Member> memberList = memberService.getMemberList(new Member());
        model.addAttribute("memberList", memberList);
        MedicalRecord medicalRecord = new MedicalRecord();

        if (member != null && member.getMemberId() != null) {
            model.addAttribute("member", memberService.getMemberById(member));
            medicalRecord.setMemberId(member.getMemberId());
        } else if (memberList != null && memberList.size() > 0) {
            model.addAttribute("member", memberList.get(0));
            medicalRecord.setMemberId(memberList.get(0).getMemberId());
        } else {
            model.addAttribute("member", null);
            medicalRecord.setMemberId(-1L);
        }

        model.addAttribute("healthRecordList", medicalRecordMapper.getMedicalRecordList(medicalRecord));

        return "health_record_index";
    }
}

